package com.espier.t9keyboard;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


public class ContactsCalllogDBUtils {
	
	private static final String TAG = "ContactProvider";
	private static final String SORT_KEY = "sort_key";
	private static final String PHOTO_ID = "photo_id";
    
    public static class CallLogQuery{
    	private static final String[] CALLLOG_PROJECTION=	new String[]{
    		Calls._ID,
    		Calls.CACHED_NAME,
    		Calls.NUMBER,
    		Calls.DATE,
    		Calls.TYPE,
    		Calls.DURATION
//    		Calls.PHONE_ID,
//    		Calls.CONTACT_ID,
    	};
    	
        public static final int INDEX_ID              = 0;
        public static final int INDEX_CACHED_NAME     = 1;
        public static final int INDEX_NUMBER     = 2;
        public static final int INDEX_DATE  = 3;
        public static final int INDEX_TYPE   = 4;
        public static final int INDEX_DURATION         = 5;
        public static final int INDEX_PHONE_ID        = 6;
        public static final int INDEX_CONTACT_ID       = 7;
    }
    
    
    public static List<MyCallLog> getCallLogs(Context context,String searchNumber){
    	
    	List<MyCallLog> callLogList = new ArrayList<MyCallLog>();
    	ContentResolver resolver = context.getContentResolver();
    	
    	Cursor cursor;
    	String selection=null;
    	String[] selectionArgs=null;
    	//Log.d("searchNumber", "searchNumber:"+searchNumber);
    	if(searchNumber!=null&&searchNumber.length()>0){
    		searchNumber=searchNumber.replace("-", "");
    		searchNumber=searchNumber.replace(" ", "");
    		//replace(//s+/g,"")
    		selection=Calls.NUMBER+" LIKE \'%"+searchNumber+"%\'";
    		//selectionArgs=new String[]{searchNumber};
    	}
    	//Log.d("searchNumber", "searchNumber:"+searchNumber);
		cursor = resolver.query(CallLog.Calls.CONTENT_URI, CallLogQuery.CALLLOG_PROJECTION, selection, selectionArgs, null);
		while (cursor.moveToNext()) {
			MyCallLog callLog = new MyCallLog();
			
			callLog.set_ID(CallLogQuery.INDEX_ID);
			
			callLog.setName(cursor.getString(CallLogQuery.INDEX_CACHED_NAME));
			
			String number = cursor.getString(CallLogQuery.INDEX_NUMBER);
			callLog.setNumber(number);
			
			callLog.setCallDate(cursor.getLong(CallLogQuery.INDEX_DATE));
			
			callLog.setType(cursor.getInt(CallLogQuery.INDEX_TYPE));
			
			callLog.setDuration(cursor.getInt(CallLogQuery.INDEX_DURATION));
			
//			callLog.setPhoneId(cursor.getInt(CallLogQuery.INDEX_PHONE_ID));
//			
//			int contactId=cursor.getInt(CallLogQuery.INDEX_CONTACT_ID);
//			callLog.setContactId(contactId);

			callLogList.add(callLog);
		}
		if(cursor!=null&&!cursor.isClosed()){
			cursor.close();
		}
    	return callLogList;
    }
     
//    /**
//     * search data is too slow
//     * @param context
//     * @param searchNumber
//     * @return
//     */
//    @Deprecated
// 	public static List<Contact> getContacts(Context context,String searchNumber) {
//		List<Contact> contactList = new ArrayList<Contact>();
//		ContentResolver resolver = context.getContentResolver();
//		Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//		
//		Log.d("searchNumber", "getContacts searchNumber:"+searchNumber);
//		String selection=null;
//		boolean isSearchNumber=false;
//    	if(searchNumber!=null&&searchNumber.length()>0){
//    		isSearchNumber=true;
//    		searchNumber=searchNumber.replace("-", "");
//    		searchNumber=searchNumber.replace(" ", "");
//    	}
//    	//Log.d("searchNumber", "getContacts searchNumber:"+searchNumber);
//    	
//		while (cursor.moveToNext()) {
//			Contact contact = new Contact();
//			String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//			contact.setContactId(contactId);
//			Log.i(TAG, "…contactId…" + contactId);
//
//			String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//			//Log.i(TAG, "…name…" + name);
//			contact.setName(name);
//			
//			String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
//			if (hasPhone.equalsIgnoreCase("1")) {
//				hasPhone = "true";
//				
//			} else {
//				hasPhone = "false";
//				if(isSearchNumber){
//					continue;
//				}
//			}
//			
//			Bitmap contactPhoto;
//			long photoId = cursor.getLong(cursor.getColumnIndex(PHOTO_ID));
//			if (photoId > 0) {
//				Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
//				InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
//				contactPhoto = BitmapFactory.decodeStream(input);
//				contact.setContactPhoto(contactPhoto);
//			} else {
//				contactPhoto = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_contacts);
//				contact.setContactPhoto(contactPhoto);
//			}
//			
//			String sortKey = cursor.getString(cursor.getColumnIndex(SORT_KEY));
//			if (!TextUtils.isEmpty(sortKey)) {
//				contact.setSortKey(sortKey);
//			} else {
//				contact.setSortKey("");
//			}
//
//			
//			if (Boolean.parseBoolean(hasPhone)) {
//				if(isSearchNumber){
//					selection=ContactsContract.CommonDataKinds.Phone.NUMBER+" LIKE \'%"+searchNumber+"%\'";
//					selection=selection+" AND "+ ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId;
//				}else{
//					selection= ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId;
//				}
//				Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,selection, null, null);
//				if(phones==null||phones.getCount()<1){
//					continue;
//				}
//				while (phones.moveToNext()) {
//					String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//					if (TextUtils.isEmpty(number)) {
//						contact.setPhoneNum("");
//						contact.setTelephonNum("");
//					} else {
//						if (number.startsWith("1")) {
//							contact.setPhoneNum(number);
//						} else if (number.startsWith("0")) {
//							contact.setTelephonNum(number);
//						}
//					}
//					Log.i(TAG, "…phoneNumber…  " + number);
//				}
//				phones.close();
//			}
//
//		
//			Cursor emails = context.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
//			while (emails.moveToNext()) {
//				String email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//				if (TextUtils.isEmpty(email)) {
//					contact.setEmail("");
//				} else {
//					contact.setEmail(email);
//				}
//				Log.i(TAG, "…emailAddress…  " + email);
//			}
//			emails.close();
//
//		
//			Cursor addrCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
//			if (addrCursor.moveToFirst()) {
//				String address = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
//				contact.setAddress(address);
//			}
//			addrCursor.close();
//
//			contactList.add(contact);
//		}
//		if(cursor!=null&&!cursor.isClosed()){
//			cursor.close();
//		}
//		return contactList;
//	}
 	
 	
 	public static  ArrayList <ContactPerson> getContactList(Context context,String searchNumber) { 
         
 		Log.d("searchNumber", "getContacts searchNumber:"+searchNumber);
		String selection=null;
    	if(searchNumber!=null&&searchNumber.length()>0){
    		searchNumber=searchNumber.replace("-", "");
    		searchNumber=searchNumber.replace(" ", "");
    		selection=Phone.NUMBER +" LIKE \'%"+searchNumber+"%\'";
    	}
         
         ArrayList<ContactPerson> contactPersonList = new ArrayList<ContactPerson>();
         String[] projection= {Phone.CONTACT_ID,Phone.DISPLAY_NAME, Phone.NUMBER, Phone.PHOTO_ID,SORT_KEY,Phone.IS_PRIMARY};
         
         Cursor cur=context.getContentResolver().query(Phone.CONTENT_URI, projection, selection, null, "sort_key COLLATE LOCALIZED ASC");
         
         boolean isSameContact;
         while(cur.moveToNext()) {
             String contactId = cur.getString(cur.getColumnIndex(Phone.CONTACT_ID));
             String number = cur.getString(cur.getColumnIndex(Phone.NUMBER));
             String isPrimary  = cur.getString(cur.getColumnIndex(Phone.IS_PRIMARY));
             ContactPhone contactPhone=new ContactPhone();
     		 isSameContact=false;
    		 for(int i=0;i<contactPersonList.size();i++){
    			if(contactPersonList.get(i).getContactId().equals(contactId)){
    				contactPhone.setNumber(number);
    				contactPhone.setIsPrimary(isPrimary);
    				contactPersonList.get(i).getPhone().add(contactPhone);
    				isSameContact=true;
    			}
    		 }
    		 if(isSameContact){
    			continue;
    		 }
    		
             ContactPerson person = new ContactPerson(context);
             ArrayList<ContactPhone> phone = new ArrayList<ContactPhone>();
             
             String name = cur.getString(cur.getColumnIndex(Phone.DISPLAY_NAME));
             String photo_id = cur.getString(cur.getColumnIndex(Phone.PHOTO_ID));
             String sort_key = cur.getString(cur.getColumnIndex("sort_key"));
             //Log.i("contacts>>>", "name:" + name + " number:" + number + " photo:"+photo_id+" id :"+id);
             
             person.setContactId(contactId);
             person.setName(name);
             person.setPhotoId(photo_id);
             person.setSortKey(sort_key);
             
             contactPhone.setIsPrimary(isPrimary);
             contactPhone.setNumber(number);
             phone.add(contactPhone);
             person.setPhone(phone);
             
             contactPersonList.add(person);
         }
         cur.close();
         return contactPersonList;
     }
 	
 	 

}
